package com.cnswhy.cloud.server.comsumer.aspect;

import com.cnswhy.cloud.common.logging.constant.MDCConstant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author xuefrye
 */
@Aspect
@Slf4j
@Component
public class LogAspect {


    @Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)||@annotation(org.springframework.amqp.rabbit.annotation.RabbitListener)")
    public void pointCut() {
    }
    /**
     * 为所有的HTTP请求添加线程号
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Around(value = "pointCut()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 方法执行前加上线程号
        String traceId = UUID.randomUUID().toString().replaceAll("-", "");
        MDC.put(MDCConstant.LOG_TRACE_ID, traceId);
        //log.info("add traceId:{}",traceId);
        // 执行拦截的方法
        joinPoint.proceed();
        // 方法执行结束移除线程号
        MDC.remove(MDCConstant.LOG_TRACE_ID);
    }
}
